# -*- coding: utf-8 -*-
# @Time : 2020/10/31 13:15
# @Author : Houor
# @Site : https://my.oschina.net/houor
# @File : golden_section.py
# @Description: 黄金分割(0.618)法

from ods.functions import tri_equation

func = tri_equation

flag = False
t = 0.618
epsilon = 1e-6

a = 0
b = 2

idx = 1

x1 = a + (1 - t) * (b - a)
x2 = a + t * (b - a)

f1 = func(x1)
f2 = func(x2)

while not flag:

    print('idx = ', idx, ':')
    print('\t\t 缩减区间前:')
    print('\t\ta = ', a, ', b = ', b)
    print('\t\tx1 = ', x1, ', x2 = ', x2)
    print('\t\tf1 = ', f1, ', f2 = ', f2)

    if f1 > f2:
        a = x1
        x1 = x2
        x2 = a + t * (b - a)

        f1 = f2
        f2 = func(x2)
        pass
    else:
        b = x2
        x2 = x1
        x1 = a + (1 - t) * (b - a)

        f2 = f1
        f1 = func(x1)
        pass

    print('\t\t 缩减区间后:')
    print('\t\t a = ', a, ', b = ', b)
    print('\t\tx1 = ', x1, ', x2 = ', x2)
    print('\t\tf1 = ', f1, ', f2 = ', f2)
    print('\t\t|b-a| = ', b - a)
    idx = idx + 1

    if abs(b - a) < epsilon:
        flag = True

    pass

print('x = (a + b) / 2 = ', (a + b) / 2)
